package org.zyj.io.idle;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import org.zyj.io.protocal.Message;

import java.util.List;

/**
 * 无需考虑半包粘包问题, 直接帮你处理好了
 */
public class ReplayingMessageDecoder extends ReplayingDecoder<Message> {

    //编写这个方法的时候, 可以把in这个参数, 当做已经读取好一条报文的所有数据来处理
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int length = in.readInt();
        int version = in.readInt();
        int opCode = in.readInt();
        int streamId = in.readInt();
        byte[] body = new byte[length];
        for (int i = 0; i < length; i++) {
            body[i] = in.readByte();
        }
        //组装message对象
        Message message = new Message();
        message.setVersion(version);
        message.setOpCode(opCode);
        message.setStreamId(streamId);
        message.setBody(body);
        out.add(message);
    }
}
